package com.probox.common.entity.service.auth;

import cn.hutool.core.util.ObjectUtil;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.constant.UserConstants;
import com.probox.common.core.enums.UserStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.ServletUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.ip.IpUtils;
import com.probox.common.entity.domain.system.SysLogininfor;
import com.probox.customer.api.domain.CustomerInfoAccount;
import com.probox.common.entity.service.customer.ICustomerInfoAccountService;
import com.probox.common.entity.service.system.ISysLogininforService;
import com.probox.common.entity.service.system.ISysUserService;
import com.probox.systemApi.domain.SysUser;
import com.probox.systemApi.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录校验方法
 *
 * @author usoft
 */
@Component
public class SysLoginService {


    @Autowired
    private ISysLogininforService logininforService;

    @Autowired
    private ISysUserService iSysUserService;


    @Autowired
    private ICustomerInfoAccountService customerInfoAccountService;

    /**
     * app/小程序登录
     */
    public LoginUser Applogin(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new BaseException("用户/密码必须填写");
        }
        // 查询客户信息
        CustomerInfoAccount customerInfoAccount = customerInfoAccountService.selectUserByUserName(username);
        if (StringUtils.isNull(customerInfoAccount)) {
            throw new BaseException("用户名或密码错误");
        }
        LoginUser userInfo = new LoginUser();
        userInfo.setCustomerInfoAccount(customerInfoAccount);


        if (!userInfo.getCustomerInfoAccount().getAccountName().equals(username) || !userInfo.getCustomerInfoAccount().getAccountPassword().equals(password)) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "用户名或密码错误");
            throw new BaseException("用户名或密码错误");
        }
        if (StringUtils.isNull(userInfo)) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new BaseException("登录用户：" + username + " 不存在");
        }
        saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    /**
     * 登录
     */
    public LoginUser login(String username, String password, String wxCode) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new BaseException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new BaseException("用户名不在指定范围");
        }
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 查询用户信息
        LoginUser userResult = iSysUserService.info(username);

        if (StringUtils.isNull(userResult)) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new BaseException("登录用户：" + username + " 不存在");
        }
        SysUser user = userResult.getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");

            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
            saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码错误");
            throw new BaseException("用户不存在/密码错误");
        }
        saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        /**
         * 保存opneiD
         */
        if (ObjectUtil.isNotEmpty(wxCode)) {
            iSysUserService.saveOpenId(wxCode, user.getUserId());
        }
        return userResult;
    }

    public void logout(String loginName) {
        saveLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 保存访问记录
     *
     * @param username 用户名称
     * @param status   状态
     * @param message  消息
     * @return 结果
     */
    private void saveLogininfor(String username, String status, String message) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());

        // 封装对象
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ip);
        logininfor.setMsg(message);
        // 日志状态
        if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
            logininfor.setStatus("0");
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus("1");
        }
        logininforService.insertLogininfor(logininfor);
    }

}
